package com.xhwl.centiotdata.suppliersystem.lifang;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.DaHuaConstant;
import com.xhwl.centiotdata.pojo.constant.LiFangConstant;
import com.xhwl.centiotdata.pojo.dto.lifang.PedestrianRecordLiFangDTO;
import com.xhwl.centiotdata.pojo.dto.lifang.UserLiFangDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.common.dto.auth.PedestrianAuthDTO;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.pedes.AuthDTO;
import com.xhwl.common.enums.pedestrian.DoorActionEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.auth.AuthAccountMapping;
import com.xhwl.common.utils.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author: yanyixiong
 * @Description:
 * @Date: create in 16:20 2022/7/11
 */
@Slf4j
@Service
public class PedestrianLiFangHandler {

    @Autowired
    private GeneralLiFangHandler generalLiFangHandler;

    public List<PedestrianRecordLiFangDTO> pullRecord(PedestrianIntegrationConfigDTO configDTO) {
        List<PedestrianRecordLiFangDTO> recordLiFangDTOList = new ArrayList<>();
        Integer pageNum = 1;
        List<PedestrianRecordLiFangDTO> recordList = null;
        do {
            recordList = this.requestRecord(pageNum, configDTO);
            if (CollectionUtils.isEmpty(recordList)) {
                break;
            }
            recordLiFangDTOList.addAll(recordList);
            ++pageNum;
        } while (!CollectionUtils.isEmpty(recordList) && recordList.size() == 500);
        return recordLiFangDTOList;
    }

    private List<PedestrianRecordLiFangDTO> requestRecord(Integer pageNum, PedestrianIntegrationConfigDTO configDTO) {
        HashMap<String, Object> params = new HashMap<>(2);
        params.put("curPage", pageNum);
        params.put("pageSize", 500);
        // 时间范围：1~10；11~20；21~30；31~40；41~50；51~00
        params.put("start", getIntervalSeconds(null, -9));
        params.put("end", getIntervalSeconds(null, 0));
        JSONObject resultObject = generalLiFangHandler.post(LiFangConstant.QUERY_ACCESS_RECORD, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        Integer result = resultObject.getInteger("result");
        if (result != 200) {
            log.error("post path:{};errMsg:{}", LiFangConstant.QUERY_DOOR, resultObject.getString("resultInfo"));
            return null;
        }
        JSONObject obj = resultObject.getJSONObject("obj");
        if (Objects.isNull(obj)) {
            log.error("post path:{};data is null!", LiFangConstant.QUERY_DOOR);
            return null;
        }
        String list = obj.getString("list");
        if (StringUtils.isEmpty(list)) {
            log.error("post path:{};data is null!", LiFangConstant.QUERY_DOOR);
            return null;
        }
        List<PedestrianRecordLiFangDTO> recordList = JSONObject.parseArray(list, PedestrianRecordLiFangDTO.class);
        if (CollectionUtils.isEmpty(recordList)) {
            return null;
        }
        return recordList;
    }

    public String getIntervalSeconds(Date date, int interval) {
        Calendar calendar = Calendar.getInstance();
        if (date == null) {
            calendar.setTime(new Date());
        } else {
            calendar.setTime(date);
        }
        calendar.set(Calendar.SECOND, (calendar.get(Calendar.SECOND)) / 10 * 10);
        calendar.add(Calendar.SECOND, interval);
        Date resultDate = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(resultDate);
    }

    public ResultJson remoteOpenDoor(PedestrianIntegrationConfigDTO pedestrianIntegrationConfigDTO, DeviceDTO deviceDTO, DoorActionEnum doorAction) {
        String api;
        switch (doorAction) {
            case REMOTELY_OPEN:
                api = LiFangConstant.REMOTE_OPEN_DOOR;
                break;
            default:
                return ResultJson.fail("无对应设备");
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("doorId", deviceDTO.getThirdDeviceId());
        params.put("opt", "remoteOpen");
        JSONObject resultObject = generalLiFangHandler.post(api, params, pedestrianIntegrationConfigDTO.getProjectId(), pedestrianIntegrationConfigDTO.getProductId(), pedestrianIntegrationConfigDTO.getIpAndPort(), pedestrianIntegrationConfigDTO.getLoginName(), pedestrianIntegrationConfigDTO.getPassword());
        if (resultObject == null) {
            log.error("post path:{};errMsg:{}", api, resultObject.getString("errMsg"));
            return ResultJson.fail("操作失败");
        }
        return ResultJson.success();
    }

    public String createUser(PedestrianIntegrationConfigDTO configDTO, UserLiFangDTO userLiFangDTO) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("employeeName",userLiFangDTO.getName());
        params.put("departId",userLiFangDTO.getDeptId());
        params.put("employeeType",userLiFangDTO.getUserType());
        params.put("employeeId",userLiFangDTO.getPaperNumber());
        params.put("phone",userLiFangDTO.getPhone());
        params.put("employeeSex",userLiFangDTO.getSex());
        params.put("empAddress",userLiFangDTO.getAddress());
        params.put("employeePass",userLiFangDTO.getPassword());
        JSONObject resultObject = generalLiFangHandler.post(LiFangConstant.CREATE_USER, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null|| resultObject.getInteger("result") != 200) {
            log.error("post path:{};errMsg:{}", LiFangConstant.CREATE_USER,resultObject.getString("errMsg"));
        }
        String data = resultObject.getString("resultInfo");
        return data;
    }

    public void createAuth(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO pedestrianAuthDTO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("sysNo",pedestrianAuthDTO.getUserOpenId());
        if (CollectionUtils.isEmpty(pedestrianAuthDTO.getAddedThirdDeviceIdList())) {
            params.put("doorIdList", pedestrianAuthDTO.getThirdDeviceIdList().stream().collect(Collectors.joining(",")));
        }else {
            params.put("doorIdList", pedestrianAuthDTO.getAddedThirdDeviceIdList().stream().collect(Collectors.joining(",")));
        }
        params.put("startTime",(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(pedestrianAuthDTO.getValidStartTime()));
        params.put("endTime",(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(pedestrianAuthDTO.getValidEndTime()));
        params.put("isSpecial",0);
        JSONObject resultObject = generalLiFangHandler.post(LiFangConstant.CREATE_AUTH, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword());
        if (resultObject == null) {
            log.error("post path:{};errMsg:{}", LiFangConstant.CREATE_AUTH,resultObject.getString("errMsg"));
        }
    }

    public ResultJson deleteAuth(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO pedestrianAuthDTO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("sysNo", pedestrianAuthDTO.getUserOpenId());
        params.put("doorIdList", pedestrianAuthDTO.getDeletedThirdDeviceIdList().stream().collect(Collectors.joining(",")));
        JSONObject resultObject = generalLiFangHandler.post(LiFangConstant.DELETE_AUTH,params,configDTO.getProjectId(),configDTO.getProductId(),configDTO.getIpAndPort(),configDTO.getLoginName(),configDTO.getPassword());
        if (resultObject == null || resultObject.getInteger("result") != 200) {
            log.error("post path:{};errMsg:{}", LiFangConstant.DELETE_AUTH, resultObject.getString("errMsg"));
            return ResultJson.fail("操作失败");
        }
        return ResultJson.success();
    }
    public List<String> findAuth(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO pedestrianAuthDTO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("sysNo",pedestrianAuthDTO.getUserOpenId());
        JSONObject resultObject = generalLiFangHandler.post(LiFangConstant.QUERY_AUTH,params,configDTO.getProjectId(),configDTO.getProductId(),configDTO.getIpAndPort(),configDTO.getLoginName(),configDTO.getPassword());
        if (resultObject==null || resultObject.getInteger("result") != 200){
            log.error("post path:{};errMsg:{}", LiFangConstant.QUERY_AUTH,resultObject.getString("errMsg"));
        }
        JSONArray jsonArray = resultObject.getJSONArray("responseData");
        List<String> deleteDoorIds = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            deleteDoorIds.add(jsonArray.getJSONObject(i).getInteger("doorId").toString());
        }
        return deleteDoorIds;
    }
    public ResultJson addPhoto(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO pedestrianAuthDTO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("sysNo",Integer.valueOf(pedestrianAuthDTO.getUserOpenId()));
        params.put("photoBase64",pedestrianAuthDTO.getImageBase());
        JSONObject resultObject = generalLiFangHandler.post(LiFangConstant.ADD_PHOTO,params,configDTO.getProjectId(),configDTO.getProductId(),configDTO.getIpAndPort(),configDTO.getLoginName(),configDTO.getPassword());
        if (resultObject==null || resultObject.getInteger("result") != 200){
            log.error("post path:{};errMsg:{}", LiFangConstant.ADD_PHOTO,resultObject.getString("errMsg"));
        }
        return ResultJson.success();
    }
    public ResultJson sendCard(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO pedestrianAuthDTO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("SysNo",Integer.valueOf(pedestrianAuthDTO.getUserOpenId()));
        params.put("Serial",pedestrianAuthDTO.getCardNumber());
        JSONObject resultObject = generalLiFangHandler.post(LiFangConstant.SEND_CARD,params,configDTO.getProjectId(),configDTO.getProductId(),configDTO.getIpAndPort(),configDTO.getLoginName(),configDTO.getPassword());
        if (resultObject==null || resultObject.getInteger("result") != 200){
            log.error("post path:{};errMsg:{}", LiFangConstant.SEND_CARD,resultObject.getString("errMsg"));
        }
        return ResultJson.success();
    }
    public ResultJson getQrCode(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO pedestrianAuthDTO){
        HashMap<String, Object> params = new HashMap<>();
        params.put("serial",pedestrianAuthDTO.getCardNumber());
        params.put("validTime",pedestrianAuthDTO.getValidTime());
        JSONObject resultObject = generalLiFangHandler.post(LiFangConstant.GET_QR_CODE,params,configDTO.getProjectId(),configDTO.getProductId(),configDTO.getIpAndPort(),configDTO.getLoginName(),configDTO.getPassword());
        if (resultObject==null || resultObject.getInteger("result") != 200){
            log.error("post path:{};errMsg:{}", LiFangConstant.GET_QR_CODE,resultObject.getString("errMsg"));
        }
        String qccode = resultObject.getString("qrcode");
        return ResultJson.success(qccode);
    }
}
